/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * formularioConvenio.java
 *
 * Created on 20-10-2012, 02:40:55 PM
 */
package SubsistemaFinanzas;

import clienteSandraParada.Login;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import java.awt.Color;
import java.awt.Desktop;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Jacqueline
 */
public class formularioConvenio extends javax.swing.JDialog {
    service.Convenio convenio;
    private Convenios p;

    /** Creates new form formularioConvenio */
    public formularioConvenio(java.awt.Frame parent, boolean modal,Convenios convenios) {
        super(parent, modal);
        initComponents();
        setIconImage(new ImageIcon(getClass().getResource("/GUI/Img/logo2.png")).getImage());
        p=convenios;
        convenio = new service.Convenio();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel11 = new javax.swing.JPanel();
        jLabel11 = new javax.swing.JLabel();
        jLabel13 = new javax.swing.JLabel();
        nombres = new javax.swing.JTextField();
        rutConvenio = new componentes.Rut();
        jLabel6 = new javax.swing.JLabel();
        formaPago = new javax.swing.JComboBox();
        jLabel7 = new javax.swing.JLabel();
        fechaInicio = new com.toedter.calendar.JDateChooser();
        jLabel8 = new javax.swing.JLabel();
        porcentaje = new componentes.Porcentaje();
        jLabel9 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        observacion = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        fechaTermino = new com.toedter.calendar.JDateChooser();
        accion = new javax.swing.JButton();
        cancelar = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        apellidoPaterno = new javax.swing.JTextField();
        apellidoMaterno = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        jLabel14 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        mensajeriaFormulario = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel11.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos Convenio"));
        jPanel11.setForeground(new java.awt.Color(102, 255, 51));

        jLabel11.setText("Rut :");

        jLabel13.setText("Nombres: ");

        jLabel6.setText("Forma de pago:");

        formaPago.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Efectivo", "Cheque", "Cuenta Corriente" }));

        jLabel7.setText("Fecha inicio:");

        jLabel8.setText("Porcentaje:");

        jLabel9.setText("Observación:");

        observacion.setColumns(20);
        observacion.setRows(5);
        jScrollPane1.setViewportView(observacion);

        jLabel1.setText("Fecha termino:");

        accion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Agregar.png"))); // NOI18N
        accion.setText("Agregar");
        accion.setToolTipText("Agregar");
        accion.setAlignmentY(0.0F);
        accion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                accionActionPerformed(evt);
            }
        });

        cancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Cancelar.png"))); // NOI18N
        cancelar.setText("Cancelar");
        cancelar.setToolTipText("Eliminar");
        cancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelarActionPerformed(evt);
            }
        });

        jLabel2.setText("Apellido paterno:");

        jLabel3.setText("Apellido materno:");

        jLabel10.setText("*");

        jLabel14.setText("*");

        jLabel4.setText("* Datos obligatorios");

        mensajeriaFormulario.setText("Área de mensajería");

        javax.swing.GroupLayout jPanel11Layout = new javax.swing.GroupLayout(jPanel11);
        jPanel11.setLayout(jPanel11Layout);
        jPanel11Layout.setHorizontalGroup(
            jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel11Layout.createSequentialGroup()
                .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel11Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel11Layout.createSequentialGroup()
                                .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel11)
                                    .addComponent(jLabel13)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel6)
                                    .addComponent(jLabel7)
                                    .addComponent(jLabel1)
                                    .addComponent(jLabel8)
                                    .addComponent(jLabel9))
                                .addGap(18, 18, 18)
                                .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(rutConvenio, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(jPanel11Layout.createSequentialGroup()
                                        .addComponent(porcentaje, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jLabel14, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(formaPago, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(nombres, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(jPanel11Layout.createSequentialGroup()
                                        .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                            .addComponent(fechaInicio, javax.swing.GroupLayout.DEFAULT_SIZE, 132, Short.MAX_VALUE)
                                            .addComponent(fechaTermino, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addComponent(apellidoPaterno, javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(apellidoMaterno, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 155, Short.MAX_VALUE))
                                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 303, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addComponent(jLabel4)))
                    .addGroup(jPanel11Layout.createSequentialGroup()
                        .addGap(154, 154, 154)
                        .addComponent(mensajeriaFormulario, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(57, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel11Layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(accion)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cancelar)
                .addGap(23, 23, 23))
        );
        jPanel11Layout.setVerticalGroup(
            jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel11Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(rutConvenio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel11Layout.createSequentialGroup()
                        .addComponent(nombres, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(apellidoPaterno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(apellidoMaterno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(formaPago, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel6)))
                    .addComponent(jLabel13, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel11Layout.createSequentialGroup()
                        .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(fechaInicio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel7))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel1)
                            .addComponent(fechaTermino, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(jLabel10))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel8, javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(porcentaje, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel14))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel11Layout.createSequentialGroup()
                        .addComponent(jLabel9)
                        .addGap(94, 94, 94)
                        .addComponent(jLabel4))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel11Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(accion)
                    .addComponent(cancelar))
                .addGap(18, 18, 18)
                .addComponent(mensajeriaFormulario))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void accionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_accionActionPerformed
        // Accion formulario
        // Boton de la accion del formulario
        if (this.getTitle().equals("Agregar Convenio")) {
            boolean duplicada = convenioDuplicado(rutConvenio.getRut().getText());
            boolean datosObligatorios = llenoDatosObligatorios();
            if(duplicada==false && datosObligatorios==true){
                Convenios.agregarConvenioBD(rutConvenio.getRut().getText(),(String)formaPago.getSelectedItem(),
                        capturarFecha("fechaInicio"),capturarFecha("fechaTermino"),porcentaje.getPorcentaje().getText(),
                        observacion.getText(),true);
                p.cargarTablaConvenios((java.util.List<service.Convenio>) listarConvenios());
            }else if(duplicada==true){
                this.mensajeriaFormulario.setText("El convenio ya se encuentra en el sistema");
                this.mensajeriaFormulario.setForeground(Color.red);
            }
            else if(datosObligatorios==false){
                this.mensajeriaFormulario.setText("Complete los campos obligatorios");
                this.mensajeriaFormulario.setForeground(Color.red);
            }
            if(duplicada==false && datosObligatorios==true){
                this.dispose();
            }
        } else if (this.getTitle().equals("Modificar Convenio")) {
            Convenios.modificarConvenioBD(rutConvenio.getRut().getText(),(String)formaPago.getSelectedItem(),capturarFecha("fechaInicio"),
                        capturarFecha("fechaTermino"),porcentaje.getPorcentaje().getText(),observacion.getText(),true);
                p.cargarTablaConvenios((java.util.List<service.Convenio>) listarConvenios());
                this.dispose();
        } else if (this.getTitle().equals("Ver Convenio")) {
            service.Privilegios p = (service.Privilegios) cargarPrivilegios(Login.getUser().getRut());
            if (p.isExportarConvenio()) {
                this.dispose();
                convenio = Convenios.buscarConvenio(this.rutConvenio.getRut().getText());
                try {
                    imprimirConvenio(convenio);
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(formularioConvenio.class.getName()).log(Level.SEVERE, null, ex);
                } catch (DocumentException ex) {
                    Logger.getLogger(formularioConvenio.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else {
                JOptionPane.showMessageDialog(this, "No tiene permisos para esta acción, \n contacte al administrador para más información");
            }
        }
    }//GEN-LAST:event_accionActionPerformed

    private void cancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_cancelarActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    public javax.swing.JButton accion;
    private javax.swing.JTextField apellidoMaterno;
    private javax.swing.JTextField apellidoPaterno;
    public javax.swing.JButton cancelar;
    private com.toedter.calendar.JDateChooser fechaInicio;
    private com.toedter.calendar.JDateChooser fechaTermino;
    private javax.swing.JComboBox formaPago;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel11;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel mensajeriaFormulario;
    private javax.swing.JTextField nombres;
    private javax.swing.JTextArea observacion;
    private componentes.Porcentaje porcentaje;
    private componentes.Rut rutConvenio;
    // End of variables declaration//GEN-END:variables

    public void limpiarFormulario() {
        this.rutConvenio.getRut().setText("");
        this.nombres.setText("");
        this.apellidoPaterno.setText("");
        this.apellidoMaterno.setText("");
        this.formaPago.setSelectedIndex(0);
        this.fechaInicio.setDate(null);
        this.fechaTermino.setDate(null);
        this.porcentaje.getPorcentaje().setText("");
        this.observacion.setText("");
    }

    public void habilitarCampos(boolean habilitar) {
        this.formaPago.setEnabled(habilitar);
        this.fechaInicio.setEnabled(habilitar);
        this.fechaTermino.setEnabled(habilitar);
        this.porcentaje.getPorcentaje().setEditable(habilitar);
        this.observacion.setEditable(habilitar);
    }
    
     public service.ProfesionalExterno buscarProfesionalExterno(String rut){
        service.ProfesionalExternoWSService service = new service.ProfesionalExternoWSService();
        service.ProfesionalExternoWS port = service.getProfesionalExternoWSPort();

        java.util.List<service.ProfesionalExterno> profesionales= port.listarProfesionalesExternos();
        //buscar paciente por el rut
        for(int i = 0; i< profesionales.size(); i++ ){
           if(profesionales.get(i).getRut().equals(rut)){
            return profesionales.get(i);
           }
        }
        return null;
    }

    public void llenarDatosFormulario(service.Convenio convenio) {
        //Llenar formulario con datos del convenio
        service.ProfesionalExterno pp= buscarProfesionalExterno(convenio.getRutInstitucion());
        this.nombres.setText(pp.getNombres());
        this.apellidoMaterno.setText(pp.getApellidoMaterno());
        this.apellidoPaterno.setText(pp.getApellidoPaterno());
        this.rutConvenio.getRut().setText(convenio.getRutInstitucion());
        this.formaPago.setSelectedItem(convenio.getFormaPago());
        this.porcentaje.getPorcentaje().setText(convenio.getPorcentaje());
        this.observacion.setText(convenio.getObservacion());
        this.fechaInicio.setDateFormatString(convenio.getFechaInicio());
        if(!convenio.getFechaInicio().equals("dd-MM-yyyy")){
            this.fechaInicio.setDate(stringToDate(convenio.getFechaInicio()));
        }
        if(!convenio.getFechaTermino().equals("dd-MM-yyyy")){
            this.fechaTermino.setDate(stringToDate(convenio.getFechaTermino()));
        }
        //inhabilitar campos que son de profesional externo y no pueden ser editados
        this.rutConvenio.getRut().setEditable(false);
        this.nombres.setEditable(false);
        this.apellidoMaterno.setEditable(false);
        this.apellidoPaterno.setEditable(false);
    }

    public Date stringToDate(String strFecha) {
        SimpleDateFormat formatoDelTexto = new SimpleDateFormat("dd-MM-yyyy");
        Date fecha = null;
        try {
            fecha = formatoDelTexto.parse(strFecha);
        } catch (ParseException ex) {
            ex.printStackTrace();
        }
        return fecha;
    }

    public String capturarFecha(String parametro) {
        Calendar cal = Calendar.getInstance();
        String fecha = "dd-MM-yyyy";
        if (parametro.equals("fechaInicio")) {
            if (this.fechaInicio.getDate() != null) {
                cal.setTime(this.fechaInicio.getDate());
                //Dia - mes - año
                fecha = Integer.toString(cal.get(Calendar.DAY_OF_MONTH)) + "-"
                        + Integer.toString(cal.get(Calendar.MONTH) + 1) + "-"
                        + Integer.toString(cal.get(Calendar.YEAR));
            }
        } else {//obtiene la fecha de termino del convenio
            if (this.fechaTermino.getDate() != null) {
                cal.setTime(this.fechaTermino.getDate());
                //Dia - mes - año
                fecha = Integer.toString(cal.get(Calendar.DAY_OF_MONTH)) + "-"
                        + Integer.toString(cal.get(Calendar.MONTH) + 1) + "-"
                        + Integer.toString(cal.get(Calendar.YEAR));
            }
        }
        return fecha;
    }

    public void configurarBotones(String formulario) {
        if (formulario.equals("agregar")) {
            this.accion.setText("Agregar");
            this.accion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Agregar.png")));
        } else if (formulario.equals("modificar")) {
            this.accion.setText("Guardar");
            this.accion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/Agregar.png")));
        } else {
            this.accion.setText("Exportar");
            this.accion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/Img/Iconos16X16/pdf.png")));
        }
    }

    public String eligeDireccionArchivo() {
        String dirArchivo = "";
        JFileChooser jFileChooser1 = new JFileChooser();
        jFileChooser1.setDialogTitle("Guardar archivo:");
        jFileChooser1.setVisible(true);

        int r = jFileChooser1.showSaveDialog(null);
        if (r == JFileChooser.APPROVE_OPTION) {
            File file = jFileChooser1.getSelectedFile();
            dirArchivo = String.valueOf(file);
        }
        dirArchivo = dirArchivo.replace('\\', '/') + ".pdf";
        return dirArchivo;

    }

    private void imprimirConvenio(service.Convenio convenio) throws FileNotFoundException, DocumentException {
        Document documento = new Document();
        String dirArchivo = eligeDireccionArchivo();

        FileOutputStream ficheroPdf = new FileOutputStream(dirArchivo);// Se crea el OutputStream para el fichero donde queremos dejar el pdf.
        // Se asocia el documento al OutputStream y se indica que el espaciado entre
        // lineas sera de 20. Esta llamada debe hacerse antes de abrir el documento
        PdfWriter.getInstance(documento, ficheroPdf).setInitialLeading(20);
        documento.open();// Se abre el documento.

        Paragraph titulo = new Paragraph("INFORMACIÓN CONVENIO");
        titulo.setAlignment(Element.ALIGN_CENTER);
        titulo.setSpacingAfter(20);
        documento.add(titulo);


        Paragraph datosPersonales = new Paragraph("Datos Profesional");
        datosPersonales.setAlignment(Element.ALIGN_LEFT);
        datosPersonales.setSpacingAfter(20);
        documento.add(datosPersonales);

        service.ProfesionalExterno pp= buscarProfesionalExterno(convenio.getRutInstitucion());

	PdfPTable table = new PdfPTable(2);
	table.addCell("Rut Profesional: ");
        table.addCell(convenio.getRutInstitucion());
        table.addCell("Nombres: ");
        table.addCell(pp.getNombres());
        table.addCell("Apellido Paterno:");
        table.addCell(pp.getApellidoPaterno());
        table.addCell("Apellido Materno:");
        table.addCell(pp.getApellidoMaterno());
        table.addCell("Forma de Pago:");
        table.addCell(convenio.getFormaPago());
        table.addCell("Fecha Inicio: ");
        table.addCell(convenio.getFechaInicio());
        table.addCell("Fecha Termino: ");
        table.addCell(convenio.getFechaTermino());
        table.addCell("Porcentaje: ");
        table.addCell(convenio.getPorcentaje());
        table.addCell("Observacion: ");
        table.addCell(convenio.getObservacion());
        documento.add(table);

        documento.close();
        abrirArchivo(dirArchivo);
    }

    public void abrirArchivo(String direccion) {
        //Abre el documento pdf
        try {
            File file = new File(direccion);
            Desktop.getDesktop().open(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Object cargarPrivilegios(java.lang.String rut) {
        service.PrivilegiosWS_Service service = new service.PrivilegiosWS_Service();
        service.PrivilegiosWS port = service.getPrivilegiosWSPort();
        return port.cargarPrivilegios(rut);
    }

    private boolean convenioDuplicado(String rutConvenio) {
        java.util.List<service.Convenio> convenios = listarConvenios();

        for (int i = 0; i < convenios.size(); i++) {
            if (convenios.get(i).getRutInstitucion().equals(rutConvenio)) {
                return true;
            }
        }
        return false;
    }

    private static java.util.List<service.Convenio> listarConvenios() {
        service.ConvenioWSService service = new service.ConvenioWSService();
        service.ConvenioWS port = service.getConvenioWSPort();
        return port.listarConvenios();
    }

    private boolean llenoDatosObligatorios() {
        if (this.rutConvenio.getRut().getText().equals("") || this.nombres.getText().equals("")
                || this.apellidoMaterno.getText().equals("") || this.apellidoPaterno.getText().equals("")
                || this.fechaInicio.getDate() == null || this.porcentaje.getPorcentaje().getText().equals("")) {
            return false;
        }
        return true;
    }

    private static Object cargarConvenio(java.lang.Long id) {
        service.ConvenioWSService service = new service.ConvenioWSService();
        service.ConvenioWS port = service.getConvenioWSPort();
        return port.cargarConvenio(id);
    }

    private static Long registrar(service.Usuario usuario, java.lang.String modulo, java.lang.String accion, java.lang.String valorAnterior, java.lang.String valorNuevo) {
        service.BitacoraWSService service = new service.BitacoraWSService();
        service.BitacoraWS port = service.getBitacoraWSPort();
        return port.registrar(usuario, modulo, accion, valorAnterior, valorNuevo);
    }
    
    public void ocultarAsteriscosFormulario(boolean ocultar){
        if(ocultar==true){
            this.jLabel10.setText("");
            this.jLabel14.setText("");
            this.jLabel4.setText("");
            this.mensajeriaFormulario.setText("");
        }else{
            this.jLabel10.setText("*");
            this.jLabel14.setText("*");
            this.jLabel4.setText("*Datos obligatorios");
            this.mensajeriaFormulario.setText("Área de mensajería");
        }
    }   
    
    public void llenarDatosFormularioProfesional(service.ProfesionalExterno pro) {
        this.rutConvenio.getRut().setText(pro.getRut());
        this.nombres.setText(pro.getNombres());
        this.apellidoPaterno.setText(pro.getApellidoPaterno());
        this.apellidoMaterno.setText(pro.getApellidoMaterno());
        //inabilitar campos puesto que son de profesional externo.. no pueden ser editados
        this.rutConvenio.getRut().setEditable(false);
        this.nombres.setEditable(false);
        this.apellidoMaterno.setEditable(false);
        this.apellidoPaterno.setEditable(false);
    }
}
